package com.mxf.code.iaop.log;

import com.alibaba.fastjson.JSONObject;
import com.mxf.code.service.CallbackService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : [mxf]
 * @version : [v1.0]
 * @className : WebLogAspect
 * @description : [描述说明该类的功能]
 * @createTime : [2022/9/10 22:47]
 * @updateUser : [mxf]
 * @updateTime : [2022/9/10 22:47]
 * @updateRemark : [描述说明本次修改内容]
 */
@Aspect
@Component
@Order(1)
@Slf4j
public class WebLogAspect {

    @Pointcut("execution(public * com.mxf.code.service1..*(..))")
    private void webLog(){}

    @Autowired
    private CallbackService callbackService;

    @Before(value = "webLog()&& @annotation(OperationLog)")
    public void doBefore(JoinPoint joinPoint) throws Throwable {;
        callbackService.doCallback("调用Before");
    }

    @Around(value = "webLog() && @annotation(OperationLog)")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        /*if (1==1){
            throw new RuntimeException("异常错误");
        }*/
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        //记录请求信息
        Object[] objs = joinPoint.getArgs();
        WebLog webLog = new WebLog();
        Object result = joinPoint.proceed();//返回的结果，这是一个进入方法和退出方法的一个分界
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        long endTime = System.currentTimeMillis();
        String urlStr = request.getRequestURL().toString();
        webLog.setBasePath(urlStr);
        webLog.setIp(request.getRemoteUser());
        webLog.setMethod(request.getMethod());
        webLog.setParameter(getParameter(method, joinPoint.getArgs()));
        webLog.setResult(JSONObject.toJSON(result));
        webLog.setSpendTime((int) (endTime - startTime));
        webLog.setStartTime(startTime);
        webLog.setUri(request.getRequestURI());
        webLog.setUrl(request.getRequestURL().toString());
        log.info("RequestAndResponse {}", JSONObject.toJSONString(webLog));
        //必须有这个返回值。可以这样理解，Around方法之后，不再是被织入的函数返回值，而是Around函数返回值
        return result;
    }

    @After(value = "webLog()&& @annotation(OperationLog)")
    public void doAfter(JoinPoint joinPoint) throws Throwable {
        callbackService.doCallback("调用After");
    }

    @AfterReturning(value = "webLog()&& @annotation(OperationLog)", returning = "ret")
    public void doAfterReturning(JoinPoint joinPoint,Object ret) throws Throwable {
        callbackService.doCallback("调用AfterReturning");
    }

    @AfterThrowing(value = "webLog()&& @annotation(OperationLog)", throwing = "e")
    public void doAfterReturning(JoinPoint joinPoint,Throwable e) throws Throwable {
        callbackService.doCallback("调用AfterThrowing");
    }
    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            } else {
                argList.add(args[i]);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }
}
